package com.lwq.project.mail.model;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
* @author 作者 linweiqiang
* @version 创建时间：2017年10月27日 下午2:32:05
* 类说明
*/
public class SendMailWithAttachment {
	
	private MimeMessage message;
	private Session session;
	private Transport transport;
	private String mailHost = "";
	private int mailHostPort = 25;
	private String username ="493671678@qq.com";
	private String password  = "kmubpnqvkhuabheg";
	private Properties properties = new Properties();
	private boolean debug = false;
	public static void main(String[] args) {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		System.out.println(sdf.format(new Date()));
//		SendMailWithAttachment smwa = new SendMailWithAttachment("493671678@qq.com", "kmubpnqvkhuabheg", "smtp.qq.com", 587, false);
		SendMailWithAttachment smwa = new SendMailWithAttachment("493671678@qq.com", "kmubpnqvkhuabheg");
		List<File> files = new ArrayList<File>();
		files.add(new File("D://test.txt"));
		List<String> list = new ArrayList<String>();
		list.add("654718842@qq.com");
		list.add("493671678@qq.com");
		list.add("13959637822@163.com");
		list.add("13959637822@139.com");
		smwa.send("测试啊啊", "<html><head></head><body><h1>hello 欢迎你!!spring image html mail</h1>"  
                + "<img src=\"http://cms-bucket.nosdn.127.net/faa4e58618d64a3d86ca61513b33729220171027131314.jpeg?imageView&thumbnail=453y225&quality=85\"/></body></html>", list , files);
		System.out.println(sdf.format(new Date()));
	}
	public SendMailWithAttachment(String username,String password) {
		this.username=username;
		this.password=password;
		mailHost = "smtp." + username.split("@")[1];
		if(mailHost.contains("qq.com")){
			mailHostPort = 587;
		}
		init();
	}
	public SendMailWithAttachment(String username,String password,String mailHost,int mailHostPort,boolean debug) {
		this.username=username;
		this.password=password;
		this.mailHost=mailHost;
		this.mailHostPort=mailHostPort;
		this.debug=debug;
		init();
	}
	private void init(){
		properties.setProperty("mail.smtp.host", mailHost);
//		properties.setProperty("mail.smtp.port", String.valueOf(mailHostPort));
		properties.setProperty("mail.smtp.auth", "true");
		properties.setProperty("mail.setder.username", username);
		properties.setProperty("mail.setder.password", password);
		session = Session.getInstance(properties);
		session.setDebug(debug);
		message = new MimeMessage(session);
	}
	
	public void send(String subject,String sendHtml,List<String> receiveUser,List<File> files){
		try {
			//发件人
			InternetAddress from  = new InternetAddress(username);
			message.setFrom(from);
			int size = receiveUser.size();
			InternetAddress[] to = new InternetAddress[size];
			//收件人
			for (int i =0;i<size;i++) {
				to[i] = new InternetAddress(receiveUser.get(i));
			}
			message.setRecipients(Message.RecipientType.TO, to);
			
			//邮件主题
			message.setSubject(subject);
			
			//像multipart对象中添加邮件的各个部分内容，包括文本内容和附件
			Multipart multipart = new MimeMultipart();
			
			//添加邮件正文
			BodyPart contentBody = new MimeBodyPart();
			contentBody.setContent(sendHtml,"text/html;charset=UTF-8");
			multipart.addBodyPart(contentBody);
			
			//添加附件
			if(files!=null){
				for (File file : files) {
					if(file.isFile()&&file!=null){
						BodyPart fileBody = new MimeBodyPart();
						DataSource source = new FileDataSource(file);
						fileBody.setDataHandler(new DataHandler(source));
						fileBody.setFileName(MimeUtility.encodeWord(file.getName()));
						multipart.addBodyPart(fileBody);
					}
				}
			}
			
			message.setContent(multipart);
			message.saveChanges();
			transport = session.getTransport("smtp");
//			transport.connect(mailHost, username, password);
			transport.connect(mailHost, mailHostPort, username, password);
			transport.sendMessage(message, message.getAllRecipients());
			System.out.println("send success!");
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			System.out.println("添加附件文件名转码失败");
			e.printStackTrace();
		}finally{
			if(transport!=null){
				try {
					transport.close();
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
